import {
    ArgumentsHost,
    BadRequestException,
    Catch,
    ExceptionFilter,
    HttpException,
    Inject,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { ResponseCode } from '../type/enum';
import { YhLoggerService } from '@/shared/yhlogger.service';
import { TypeORMError } from 'typeorm';

const errorMsg = {
    /* 1048: '存在空值',
    1054: '值错误',
    1062: '数据重复',
    1364: '非NULL值未赋值',
    1451: '存在关联数据不能删除',
    1452: '外键引用数据错误' */
}

@Catch(BadRequestException)
export class YhRequestExceptionFilter implements ExceptionFilter {
    // @Inject(YhLoggerService) private logger: YhLoggerService;
    constructor(private logger: YhLoggerService){}
    catch(exception: BadRequestException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        // const req = ctx.getRequest<Request>();
        const res = ctx.getResponse<Response>();
        // console.log(req);
        // const status = exception.getStatus();
        console.log('exception', exception);

        //const msgs = exception['response'].message.join(`<br><br>`);
        const msg = exception['response'].message ?? exception['response'];
        const context = exception.stack.split('at ')[1].split(' ')[0];
        // console.log(exception.stack.split('at '));
        this.logger.error(msg, context);
        res.status(200).json({
            code: ResponseCode.FailWithMsg,
            msg: [msg],
        });
    }
}

@Catch(HttpException)
export class YhExceptionFilter implements ExceptionFilter {
    // @Inject(YhLoggerService) private logger: YhLoggerService;
    constructor(private logger: YhLoggerService){}
    catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        // const req = ctx.getRequest<Request>();
        const res = ctx.getResponse<Response>();
        // console.log(req);
        // const status = exception.getStatus();
        console.log('exception', exception);
        
        //const msgs = exception['response'].message.join(`<br><br>`);
        const msg = exception['response'].message ?? exception['response'];
        const context = exception.stack.split('at ')[1].split(' ')[0];
        // console.log(exception.stack.split('at '));
        this.logger.error(msg, context);
        res.status(200).json({
            code: ResponseCode.FailWithMsg,
            msg: [msg],
        });
    }
}


@Catch(TypeORMError)
export class YhTypeORMErrorFilter implements ExceptionFilter<Error> {
    constructor(private logger: YhLoggerService){}
    catch(error: TypeORMError, host: ArgumentsHost) {

        const ctx = host.switchToHttp();
        const res = ctx.getResponse<Response>();
        console.log(error);
        
        this.logger.error(error.message, 'typeorm SQL 错误');
        let msg = '';
        /* if (error['errno'] === 1644) {
            msg = error['']
        } */
        res.status(200).json({
            code: ResponseCode.FailWithMsg,
            msg: [error['sqlMessage']]
            //msg: errorMsg[error['errno']] ? [errorMsg[error['errno']]] : [error['sqlMessage']]
        });
    }
}

@Catch(Error)
export class YhErrorFilter implements ExceptionFilter<Error> {
    constructor(private logger: YhLoggerService){}
    catch(error: Error, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const res = ctx.getResponse<Response>();
        console.log(error);
        
        this.logger.error(error.message, 'nestjs错误');
        res.status(200).json({
            code: ResponseCode.FailWithMsg,
            // msg: error.message,
            msg: [errorMsg[error['errno']] ? errorMsg[error['errno']] : error.message]
        });
    }
}

